package com.example.status;

import com.example.model.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Created with IntelliJ IDEA.
 * ClassName: MapStateDemo
 * Package: com.example.status
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-07-26
 * Time: 16:43
 */


public class MapStateDemo {

    public static void main(String[] args) throws Exception {
        //统计每种传感器每种水位值出现的次数

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        SingleOutputStreamOperator<WaterSensor> map = env.socketTextStream("hadoop102", 7777)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        final String[] s = value.split(" ");

                        return new WaterSensor(s[0], Long.valueOf(s[1]), Integer.valueOf(s[2]));
                    }
                });

        //KeyBy之后的状态
        map.keyBy(value -> value.getId())
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    //定义Map状态
                    ////统计每种传感器每种水位值出现的次数
                    //一个是水位值 一个是次数
                    MapState<Integer, Integer> mapState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        mapState = getRuntimeContext().
                                getMapState(new MapStateDescriptor<Integer, Integer>("mapState", Types.INT, Types.INT));

                    }

                    @Override
                    public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                    }
                }).print();

        env.execute();

    }
}
